package com.garlic.face.jlf.presenter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.text.TextUtils;

import com.alipay.xdevicemanager.api.XDeviceManager;
import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.bean.PayFlow;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.Base64Util;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author wenhui02.liu
 * @date 2018/8/13.
 */

public class BarCodePresenter implements BarCodeContract.Presenter {
    private XDeviceManager mXDeviceManager = null;
    String TAG = "BarCodePresenter";
    BarCodeContract.View mView;
    private Dialog mDialog = null;

    public BarCodePresenter(BarCodeContract.View view) {
        mView = view;
        try {
            mXDeviceManager = new XDeviceManager(App.getContext());
            mXDeviceManager.initContext();
        } catch (Exception e) {
            if (!TextUtils.isEmpty(e.getMessage())) {
                e.printStackTrace();
                LogUtils.e("BASE ACTIVITY " + e.getMessage());

            }
        }
    }


    @Override
    public void cancelPay(String reason) {
        LogUtils.d(reason, true);
        mView.showProgress();
        ServiceInterface.getInstance().cancelTrade("", "");
    }

    /*@Override
    public void scanToPay(Activity activity, String mAuthCode, String mAmount, String mDetailList) {
        try {
            Pay tr = new Pay(activity);
            tr.setOnPayListener(new Pay.PayListener() {

                @Override
                public void onStart() {
                }

                @Override
                public void onSuccess(String result) {
                    mView.toSuccssActivity(result);
                }

                @Override
                public void onError(String msg) {
                    mView.toFailureActivity(msg);
                }
            });
            tr.startPay(mAuthCode, mAmount, "bar_code", mDetailList, "", doTerminalSign(mAuthCode));
        } catch (Exception e) {
            Toasty.error(App.getContext(), ZolozUtils.SMILEPAY_TXT_FAIL).show();
        }
    }*/

    @Override
    public void payBarCode(String mPayBarCode) {
        mView.showProgress();
        LogUtils.d("mPayBarCode:" + mPayBarCode, true);

        //String payId = mPayBarCode;
//        String payId = "ALRL" + mPayBarCode + "," + doTerminalSign(mPayBarCode);
//        String payId = mPayBarCode + "," + stringToBase64(doTerminalSign(mPayBarCode));

        String partPayBarCode = mPayBarCode.substring(1, mPayBarCode.length());
        String sign = doTerminalSign(partPayBarCode);
        if(sign.length() == 0 || sign.equals(partPayBarCode)){
            mDialog = new AlertDialog.Builder(App.getActivityStack().get(App.getActivityStack().size() - 1))
                    .setTitle("错误").setMessage("请重试").setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();
            mDialog.show();
            return;
        }

        String payId = "ALTM" + partPayBarCode + "," + sign;
        LogUtils.d("payId:"+ payId, true);
        Double d_amount = Means.getInstance().getRec_Tran().getAmount();
        Double d_remain = Means.getInstance().getRec_Tran().getRemian();
        String amount = d_amount+"";
        String ytAmount = amount;
        ServiceInterface.getInstance().payTrade(JLFConstant.PAY_FACE_SCAN, "", amount, "", "", "1", ytAmount, payId);
    }

    @Override
    public void parseJson(JSONObject jsonObject) {
        String interfacetype = "";
        String retflag = "";
        String retmsg = "";
        try {
            interfacetype = jsonObject.getString("INTERFACETYPE");
            retflag = jsonObject.getString("retflag");
            retmsg = jsonObject.getString("retmsg");
            if (interfacetype.equals(JLFConstant.TAG_PAY_RESPONSE)) {
                mView.hideProgress();
                if (retflag.equals("0")) {
                    Means.getInstance().setTendCount(Means.getInstance().getTendCount() + 1);
                    PayFlow payFlow = new PayFlow();
                    payFlow.setAmount(jsonObject.getDouble("amount"));
                    payFlow.setChange(jsonObject.getDouble("change"));
                    payFlow.setFlowid(Means.getInstance().getTendCount());
                    payFlow.setKeyindex("3");
                    payFlow.setPayid(jsonObject.getString("payid"));
                    payFlow.setTrace(jsonObject.getString("trace"));
                    String receiptLines = jsonObject.getString("receiptLines");
                    if(!TextUtils.isEmpty(receiptLines)){
                        String[] receiptArray = receiptLines.replace("[","").replace("]","").split(",");
                        ArrayList<String> receiptList = new ArrayList<String>();
                        for(int i = 0; i<receiptArray.length; i++){
                            receiptList.add(receiptArray[i]);
                        }
                        Means.getInstance().setPrintBillHead(receiptList);
                    }
                    Means.getInstance().getPayHead().add(payFlow);
                    //if (jsonObject.getString("remain").equals("0.00")) {
                        //支付完成
                        LogUtils.d("支付完成回到成功界面", false);
                        mView.toSuccssActivity("");
                    //} else {
                        // TODO: 2018/7/24 部分付款
                    //}
                } else {
                    String s = String.format(App.getContext().getResources().getString(R.string.pay_error),retmsg);
                    ToastUtils.toastShow(s, ToastUtils.ERROR);
//                    mView.toFailureActivity(retmsg);
                    mView.showProgress();
                    ServiceInterface.getInstance().stateLogin();
                }
            } else if (interfacetype.equals(JLFConstant.TAG_CANCELTRADE_RESPONSE)) {
                mView.hideProgress();
                if (retflag.equals("0")) {
                    Tools.clearTrade();
                    mView.gotoMain();
                } else {
                    ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
                    LogUtils.e("取消支付" + retmsg);
                }
            } else if(interfacetype.equals(JLFConstant.TAG_STATE_RESPONSE)){
                if (retflag.equals("0")) {
                    mView.hideProgress();
                    if (retmsg.equals(JLFConstant.POS_PARTIAL_PAYMENT)) {
                        mView.toFailureActivity(retmsg, JLFConstant.SCO_PARTIAL_PAY_PSV);
                    }else {
                        mView.toFailureActivity(retmsg, "");
                    }
                }else {
                    mView.hideProgress();
                    //获取状态失败
//                    ToastUtils.toastShow("获取POS状态失败   需要重启POS", ToastUtils.ERROR);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected String doTerminalSign(String barCode) {
        try {
            int result[] = new int[1];
            String signedHelloWorld = mXDeviceManager.sign(barCode.getBytes(), result);

            if (result[0] != 0) {
                ToastUtils.toastShow("机具管控参数错误:" + result[0], ToastUtils.ERROR);
                return "";
            } else {
                return signedHelloWorld;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("BASE ACTIVITY " + e.getMessage());
            return barCode;
        }
    }

    @Override
    public void destoryMXdevice(){
        try{
            if (mXDeviceManager != null) {
                mXDeviceManager.uninitContext();
                mXDeviceManager = null;
            }
        }catch (Exception e){
            e.printStackTrace();
            LogUtils.e("BASE ACTIVITY " + e.getMessage());
        }
    }

    private String stringToBase64(String ss) {
        byte[] bytes = ss.getBytes();
        String encode = Base64Util.encode(bytes);
        return encode;
    }

}
